package com.cn.hospital.service.impl.auth;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.hospital.mapper.SysUserMapper;
import com.cn.hospital.service.auth.LoginService;
import com.cn.hospital.service.auth.SysUserService;
import com.cn.hospital.entity.LoginUser;
import com.cn.hospital.entity.SysUser;
import com.cn.hospital.message.Msg;
import com.cn.hospital.utils.AppJwtUtil;
import com.cn.hospital.utils.MD5Utils;
import com.cn.hospital.utils.RedisUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service(interfaceClass = LoginService.class)
@Log4j2
public class LoginServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements LoginService {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    RedisUtils redisUtils;


    @Override
    public Msg login(LoginUser loginUser) {

        SysUser sysUser = sysUserService.getByUsername(loginUser.getUserName());
        if (sysUser == null) {
            return new Msg<>().error(404, "用户不存在");
        }
        if (sysUser.getPassword().equals(MD5Utils.encode(loginUser.getPassword()))) {
            Map<String, Object> map = new HashMap<>();
            sysUser.setPassword("");
            String token = AppJwtUtil.getToken(sysUser.getUserId());

            /*
                Redis 存储 token
                    TimeUnit 使用
                TimeUnit.DAYS          //天
                TimeUnit.HOURS         //小时
                TimeUnit.MINUTES       //分钟
                TimeUnit.SECONDS       //秒
                TimeUnit.MILLISECONDS  //毫秒
             */
            redisUtils.set("token", token, 3600L, TimeUnit.SECONDS);
            map.put("token", token);
            map.put("user", sysUser);

            log.info("userId : " + sysUser.getUserId() + " => message : 登录成功");
            return new Msg<>().ok(200, map, "登录成功");
        } else {
            log.info("userId : " + sysUser.getUserId() + " => message : 登录失败");
            return Msg.errorResult(404, "用户名或密码错误");
        }
    }
}
